import axios from 'axios'
import qs from 'qs'
import PromiseState from './PromiseState'

const { config } = window // 本项目依赖于 window.config 的配置，格式参考 deploy-cfg-example.js

const API = axios.create({
  baseURL: config.APIRoot,
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
  }
})
// API.defaults.headers.common['content-type'] = 'text/plain';
// API.defaults.headers.common['content-type'] = 'application/x-www-form-urlencoded';

// 只有以下三种类型不会发起 Preflighted requests
// application/x-www-form-urlencoded
// multipart/form-data
// text/plain

/* eslint no-param-reassign:0 */
export default {
  methods: {
    newStore() {
      return new PromiseState()
    },
    spost(store, path, data) {
      return new Promise((resolve, reject) => {
        store.b = new Date()
        store.t = 'ajax'
        store.u = path
        store.r = data
        store.p = true
        store.o = false
        store.e = false
        store.m = ''
        store.d = {}
        store.s += 1
        data = data || {}

        // 没登录，发送 ajax 请求直接按异常处理，不实际发出请求了
        if (localStorage.getItem('token') == '') {
          store.o = false
          store.e = true
          store.m = '未登录'
          alert('请登录')
          this.$router.push('/login')
          reject(store)
          return
        }

        if (!data.token) {
          data.token = localStorage.getItem('token')
        }

        if (this.$store && this.$store.state.session) {
          Object.assign(data, this.$store.state.session.cookies)
        }
        this.$root.loading = true
        let post
        if (data.constructor.name === 'FormData') {
          post = API.post(path, data)
        } else {
          post = API.post(
            path,
            qs.stringify(data, {
              indices: false
            })
          )
        }

        post
          .then(res => {
            const d = res.data
            store.f = new Date()
            store.p = false
            store.c = 0
            store.d = d
            store.o = true
            store.e = false

            this.$root.loading = false
            this.$emit(`ajax:${store.u}`, store)
            if (typeof d == 'string' && d.indexOf('<script>') > 0) {
              alert(d.split("'")[1])
              if (d.split("'")[1].indexOf('尚未登陆系统') > 0) {
                this.$router.push('/login')
              }
              return
            }
            if (typeof d == 'object') {
              if (d.token == '') {
                console.log(d)

                alert('登录失效，请重新登录！')
                this.$router.push('/login')
                return
              }
            }
            resolve(store)
          })
          .catch(d => {
            store.f = new Date()
            store.p = false
            store.o = false
            store.e = true
            store.c = -2
            if (d.status === 404) {
              store.m = '后台服务暂未开通'
            } else {
              store.m = '服务调用异常'
            }
            store.d = d
            this.$root.loading = false
            this.$emit(`ajax:${store.u}`, store)
            reject(store)
          })
      })
    },
    sget(store, path, data) {
      return new Promise((resolve, reject) => {
        store.b = new Date()
        store.t = 'ajax'
        store.u = path
        store.r = data
        store.p = true
        store.o = false
        store.e = false
        store.m = ''
        store.d = {}
        store.s += 1
        data = Object.assign({}, data) || {}

        // 没登录，发送 ajax 请求直接按异常处理，不实际发出请求了
        if (
          this.$store &&
          this.$store.state.session &&
          !this.$store.state.session.cookies
        ) {
          store.o = false
          store.e = true
          store.m = '未登录'
          reject(store)
          return
        }
        if (this.$store && this.$store.state.session) {
          Object.assign(data, this.$store.state.session.cookies)
        }
        this.$root.loading = true
        const get = API.get(path, {
          params: data
        })
        get
          .then(res => {
            const d = res.data
            store.f = new Date()
            store.p = false
            store.o = true
            store.e = false
            store.c = 0
            store.d = d
            this.$root.loading = false
            this.$emit(`ajax:${store.u}`, store)
            resolve(store)
          })
          .catch(d => {
            store.f = new Date()
            store.p = false
            store.o = false
            store.e = true
            store.c = -2
            if (d.status === 404) {
              store.m = '后台服务暂未开通'
            } else {
              store.m = '服务调用异常'
            }
            store.d = d
            this.$root.loading = false
            this.$emit(`ajax:${store.u}`, store)
            reject(store)
          })
      })
    },
    async sleep(seconds) {
      await new Promise(resolve => {
        setTimeout(resolve, seconds * 1000)
      })
    }
  }
}
